package com.huan.study.excel.example;

import com.huan.study.excel.entity.Student;
import com.huan.study.excel.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 相同单元格的内容合并
 *
 * @author huan.fu
 * @date 2023/3/21 - 20:38
 */
public class SameCellContentMerge {

    public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
        List<Student> students = generatorData();

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("sheet-01");

        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("班级");
        row.createCell(1).setCellValue("课程");
        row.createCell(2).setCellValue("学生");
        row.createCell(3).setCellValue("年龄");

        int rowIndex = 1;
        for (Student student : students) {
            HSSFRow contentRow = sheet.createRow(rowIndex++);
            contentRow.createCell(0).setCellValue(student.getClassName());
            contentRow.createCell(1).setCellValue(student.getCourseName());
            contentRow.createCell(2).setCellValue(student.getStudentName());
            contentRow.createCell(3).setCellValue(student.getAge());
        }
        System.out.println("1");
        ExcelUtil.mergeSameCellContentColumn(sheet, 1, 0);
        System.out.println("2");
        ExcelUtil.mergeSameCellContentColumn(sheet, 1, 1);
        System.out.println("3");
        ExcelUtil.mergeSameCellContentColumn(sheet, 1, 2);
        System.out.println("4");

        workbook.write(new File("1.xlsx"));
        workbook.close();


    }

    private static List<Student> generatorData() throws NoSuchAlgorithmException {
        String[] classes = new String[]{"大一班", "大二班", "大三班"};
        String[] courseNames = new String[]{"语文", "数学", "化学", "生物"};
        String[] studentNames = new String[]{"张三", "李四"};
        SecureRandom random = SecureRandom.getInstanceStrong();
        List<Student> students = new ArrayList<>(10);
        for (String className : classes) {
            for (String courseName : courseNames) {
                for (String studentName : studentNames) {
                    students.add(new Student(className, courseName, studentName, random.nextInt(99)));
                }
            }
        }
        return students;
    }
}
